package com.dmz.questysf.server;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dmz.questysf.util.HttpHelper;
import com.dmz.questysf.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @author Laptop
 */
@Slf4j
@Component
public class YsfServer implements Runnable {

    // 监听端口，默认7111
    @Value("${csp.server.port}")
    private int CSP_SERVER_PORT;
    @Value("${cspIp1}")
    private String cspIp;
    @Value("${cspIp2}")
    private String csp1Ip;
    @Value("${cspIp4}")
    private String csp3Ip;
    @Value("${cspIp3}")
    private String csp2Ip;

    @Value("${whiteIp1}")
    private String whiteIp1;
    @Value("${whiteIp2}")
    private String whiteIp2;
    @Value("${whiteIp3}")
    private String whiteIp3;


    private SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /***
     * 启动监听线程
     */
    @Override
    public void run() {

        startServer();
    }

    /**
     * 启动监听Csp ServerSocket
     */
    public void startServer() {
        try (ServerSocket serverSocket = new ServerSocket(CSP_SERVER_PORT)) {
            log.info("{}TCP Server[{}]已经启动，开始监听......", Charset.defaultCharset().displayName(), CSP_SERVER_PORT);
            while (true) {
                Socket listenSocket = serverSocket.accept();
                listenSocket.setSoTimeout(40000);
                String ip = listenSocket.getInetAddress().toString();
                System.out.println(ip);
                System.out.println(cspIp);
                System.out.println(csp1Ip);
                System.out.println(csp3Ip);
                System.out.println(csp2Ip);
                if (ip.contains(cspIp) || ip.contains(csp1Ip) || ip.contains(csp3Ip) || ip.contains(csp2Ip)
                        || ip.contains(whiteIp1) || ip.contains(whiteIp2) || ip.contains(whiteIp3)) {
                    log.info("server 接受到 【csp】 请求的时间：{}", sdf2.format(new Date()));
                    System.out.println("接收到请求...");
                    log.info("");
                    log.info("server 接受到 【csp】 请求：");
                    // 这个函数中的代码出现异常不能影响socket服务器的继续运行
                    try {
                        processCspRequest(listenSocket);
                    } catch (Exception e) {
                        log.error(e.toString());
                    }
                }
                log.info("TCP server 结束处理：{}", sdf2.format(new Date()));
                log.info("");
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    // 处理csp请求
    private String processCspRequest(Socket cspSocket) {
        InputStream inp = null;
        InputStreamReader isr = null;
        BufferedReader bfr = null;
        OutputStream ots = null;
        String info = "";
        try {
            inp = cspSocket.getInputStream();
            isr = new InputStreamReader(inp, "GBK");
            bfr = new BufferedReader(isr);
            info = bfr.readLine();
            String in = info;
            //new String(recBuffer,AppValues.csn_U8);
            log.info("报文数据{}", in);
            // 长度判断
            if (in.length() > 4) {
                ots = cspSocket.getOutputStream();
                System.out.println(in.substring(4));
                JSONObject jsonob = JSONUtil.parseObj(in.substring(4));
                String url = (String) jsonob.get("url");
                String type = (String) jsonob.get("type");
                log.info("url:{}", url);
                //post请求
                String contentType = "application/json;charset=UTF-8";
                //	url +=path;
                JSONObject resultJSON = null;
                if ("get".equals(type)) {
                    resultJSON = HttpHelper.doGet(url);
                } else {
                    String json = jsonob.get("Data").toString();
                    resultJSON = HttpHelper.doPost3(url, json, contentType);
                }


                resultJSON = resultJSON.getJSONObject("ResponseText");
                String result = JSONUtil.toJsonStr(resultJSON);

                result = StringUtil.AddZeroForNum(result) + result;
                System.out.println(JSONUtil.toJsonStr(resultJSON));
                byte[] data = result.getBytes("GBK");
                if (data != null) {
                    String output = new String(data, "GBK");
                    log.info("返回报文为：\n{}", output);
                    ots.write(data);
                }
            }
        } catch (Exception e) {
            log.error("程序异常错误：", e);
        } finally {
            try {
                if (ots != null) {
                    ots.close();
                }
                if (bfr != null) {
                    bfr.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (inp != null) {
                    inp.close();
                }
            } catch (IOException e) {
                log.error("程序异常错误：", e);
            }

        }
        return "";
    }
}